package com.yitao.cms.service.product;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;

import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.common.excel.DataColumn;
import com.skipper.base.common.excel.DataTable;
import com.skipper.base.common.excel.ExcelConverter;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.json.JSON;
import com.skipper.base.json.JSONArray;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.constant.BaseConstant;
import com.yitao.client.constant.ProductConstant;
import com.yitao.client.constant.product.ProductRelevanceInfoEnums;
import com.yitao.client.dto.product.ProductImgDto;
import com.yitao.client.dto.product.ProductInfoDto;
import com.yitao.client.dto.product.ProductSpecificationDto;
import com.yitao.client.model.product.*;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.cashCoupons.CashCouponsProductListDto;
import com.yitao.cms.dto.product.ProductAddDto;
import com.yitao.cms.dto.product.ProductNameAndSkuDto;
import com.yitao.cms.dto.product.ProductSaleChangeDto;
import com.yitao.cms.dto.product.ProductSkuUpdateDto;
import com.yitao.cms.enums.ProductErrorEnum;
import com.yitao.cms.mapper.ProductRepository;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.service.activity.CmsProductGroupActivityService;
import com.yitao.cms.service.user.cmsUser.OperationUserService;
import com.yitao.cms.utils.*;
import com.yitao.cms.vo.product.BaseImgDto;
import com.yitao.cms.vo.product.ProductInfoVo;
import com.yitao.cms.vo.product.ProductOperationCategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Function:
 * Date: 2018/12/5
 *
 * @author skipper
 * @desc
 * @see
 */
@Service
public class ProductCmsService extends GenericEntityService<ProductInfoModel, ProductInfoDto, QProductInfoModel> {

    @Autowired
    private ProductImgService productImgService;
    @Autowired
    private ProductCmsSkuService productCmsSkuService;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private BaseProductCategoryService productCategoryService;
    @Autowired
    private ProductSpecificationService productSpecificationService;
    @Autowired
    private ProductBrandServices productBrandServices;
    @Autowired
    private BaseProductCategoryService baseProductCategoryService;
    @Autowired
    private ProductCategoryRelationService productCategoryRelationService;
    @Autowired
    private OperationProductCategoryService operationProductCategoryService;

    @Autowired
    private CmsProductGroupActivityService cmsProductGroupActivityService;
    @Autowired
    public ProductTaskLowerShelfService productTaskLowerShelfService;
    @Autowired
    private ProductLogisticsInfoService productLogisticsInfoService;
    @Autowired
    private ProductRelevanceInfoService productRelevanceInfoService;

    private BaseUtils base = BaseUtils.getInstance();

    public ProductCmsService(EntityManager entityManager) {
        super(entityManager);
    }

    /**
     * 产品添加
     *
     * @param productInfoDto
     * @return
     */
    @Transactional
    public DataOutput saveProductInfoAndImg(ProductAddDto productInfoDto, HttpServletRequest request) {
        logger.info("商品请求参数:{}", JSON.toJSONString(productInfoDto));
        Date now = new Date();
        ProductInfoDto productInfoDtoResult = new ProductInfoDto();
        ProductInfoModel productInfoModel = new ProductInfoModel();
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        //商品必填字段验证
        DataOutput dataOutput = productData(productInfoDto);
        if (dataOutput != null && dataOutput.getStatus() != CommonStatus.SUCCESS.getCode()) {
            return dataOutput;
        }

        //修改数据判断是否上架及补充固定信息
        if (productInfoDto != null && productInfoDto.getId() != null) {
            ProductInfoModel getProductInfoModel = repository.findOne(Q.id.eq(productInfoDto.getId()));
            if (null == getProductInfoModel) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "产品ID有误,未查到相关产品!");
            }
            if (true == getProductInfoModel.getIsSale()) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "产品已上架，不可编辑!");
            } else {
                BeanUtils.copyProperties(getProductInfoModel, productInfoModel);
                productInfoModel.setProductName(productInfoDto.getProductName());
                productInfoModel.setProductEnName(productInfoDto.getProductEnName());
                productInfoModel.setProductDescription(productInfoDto.getProductDescription());
                productInfoModel.setProductDetail(productInfoDto.getProductDetail());
                productInfoModel.setProductSort(productInfoDto.getProductSort());
                productInfoModel.setBrandCode(productInfoDto.getBrandCode());
                productInfoModel.setBrandName(productInfoDto.getBrandName());
                productInfoModel.setBrandEnName(productInfoDto.getBrandEnName());
                productInfoModel.setCategoryId(productInfoDto.getCategoryId());
                productInfoModel.setCategoryName(productInfoDto.getCategoryName());
                productInfoModel.setBuiltPlaceId(productInfoDto.getBuiltPlaceId());
                productInfoModel.setBuiltPlaceName(productInfoDto.getBuiltPlaceName());
                productInfoModel.setMarkerPrice(productInfoDto.getMarkerPrice());
                productInfoModel.setSalesPrice(productInfoDto.getSalesPrice());
                productInfoModel.setWholesalePrice(productInfoDto.getWholesalePrice());
                productInfoModel.setFreightFee(productInfoDto.getFreightFee());
                productInfoModel.setActivePrice(productInfoDto.getWholesalePrice());
                productInfoModel.setProductOutsideBarcode(productInfoDto.getProductOutsideBarcode());
                if (productInfoDto.getProductBannerImgDtoList() != null && productInfoDto.getProductBannerImgDtoList().size() != 0) {
                    productInfoModel.setProductMainImgUrl(productInfoDto.getProductBannerImgDtoList().get(0).getImageUrl());
                }

            }
        } else {//添加数据补充默认值
            BeanUtils.copyProperties(productInfoDto, productInfoModel);
            productInfoModel.setShopId(userSession.getShopId());
            productInfoModel.setProductType(ProductConstant.ProductTypeEnum.GENERAL.getCode());//商品类型
            productInfoModel.setProductCode(NumberingRuleUtil.newCodeByHeader(BaseConstant.PRODUCT_CODE_HEADER));
            // 默认业务类型为普通业务类型
            productInfoModel.setBusinessType(ProductConstant.BusinessTypeEnum.STORE.getCode());
            // 默认币种为人民币
            productInfoModel.setCurrency(ProductConstant.CurrencyTypeEnum.RMB.getCode());
            // 默认不上架
            productInfoModel.setIsSale(false);
            productInfoModel.setIsRecommend(false);
            productInfoModel.setCreateBy(userSession.getId());
            productInfoModel.setCreateTime(now);
            productInfoModel.setIsDelete(false);
            productInfoModel.setImageState(ProductConstant.ProductImageStateEnum.PROCESSED.getCode());//默认图片不需要处理
            if (productInfoDto.getProductBannerImgDtoList() != null && productInfoDto.getProductBannerImgDtoList().size() != 0) {
                productInfoModel.setProductMainImgUrl(productInfoDto.getProductBannerImgDtoList().get(0).getImageUrl());
            }
        }
        productInfoModel.setLastUpdateBy(userSession.getId());
        productInfoModel.setLastUpdateTime(now);
        //保存商品信息
        // logger.info("添加商品主信息参数{}",JSON.toJSONString(productInfoModel));
        ProductInfoModel saveProductInfoModel = repository.save(productInfoModel);
        logger.info("添加商品返回主信息{}", JSON.toJSONString(saveProductInfoModel));
        Optional<ProductInfoModel> productInfoModelOptional = Optional.ofNullable(saveProductInfoModel);
        if (productInfoModelOptional.isPresent()) {
            if (productInfoModel.getId() == null) {
                return new DataOutput(ProductErrorEnum.PRODUCT_CREATE_ERROR.getCode(), ProductErrorEnum.PRODUCT_CREATE_ERROR.getMsg());
            } else {
                //商品主信息新增成功 则同步数据至ES
                productRepository.save(base.convertEntityToDto(productInfoModel,
                        new ProductInfoModelForSearch()));
            }
        }
        BeanUtils.copyProperties(saveProductInfoModel, productInfoDtoResult);
        //产品库存描述
        if (!StringUtils.isEmpty(productInfoDto.getProductAssembleDesc())) {
            ProductRelevanceInfoModel productRelevanceInfoModel = productRelevanceInfoService.saveProductRelevanceInfo(saveProductInfoModel.getId(),
                    ProductRelevanceInfoEnums.TYPE.PRODUCT_ASSEMBLE_DESC, productInfoDto.getProductAssembleDesc(), userSession.getId());
        }
        //添加商品关联的URL
        if (!StringUtils.isEmpty(productInfoDto.getRelevantUrl())) {
            ProductLogisticsInfoModel productLogisticsInfoModel = new ProductLogisticsInfoModel();
            productLogisticsInfoModel.setProductId(saveProductInfoModel.getId());
            productLogisticsInfoModel.setRelevantUrl(productInfoDto.getRelevantUrl());
            productLogisticsInfoModel.setDelete(false);
            productLogisticsInfoModel.setCreateBy(userSession.getId());
            productLogisticsInfoModel.setCreateTime(base.getNow());
            productLogisticsInfoModel.setLastUpdateTime(base.getNow());
            productLogisticsInfoModel.setLastUpdateBy(userSession.getId());
            ProductLogisticsInfoModel productLogisticsInfoModel1 = productLogisticsInfoService.saveProductLogistics(productLogisticsInfoModel);
            if (productLogisticsInfoModel1 != null) {
                productInfoDtoResult.setRelevantUrl(productLogisticsInfoModel1.getRelevantUrl());
            }
        }

        //添加商品运营分类
        List<ProductCategoryRelationModel> productCategoryRelationModelList = productCategoryRelationService.addProductCategoryRelation(productInfoDto.getOperationCategoryIds(), saveProductInfoModel.getId());
        if (CollectionUtils.isEmpty(productCategoryRelationModelList)) {
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "添加商品运营分类失败!");
        } else {
            List<Long> operationIdS = productCategoryRelationModelList.stream().map(it -> it.getCategoryId()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(operationIdS)) {
                productInfoDtoResult.setOperationCategoryIds(operationIdS);
            }

        }


        /**
         * 构建商品图片信息
         */
        //冗余出的商品详情图片id字段
        List<String> imgStringIds = new ArrayList<>();
        List<ProductImgDto> productBannerImgDtoList = productInfoDto.getProductBannerImgDtoList();
        if (!CollectionUtils.isEmpty(productBannerImgDtoList)) {
            //删除之前的图片信息
            productImgService.updateProductImage(ProductConstant.ImgTypeEnum.BANNER, saveProductInfoModel);
            productBannerImgDtoList.stream().forEach(
                    e -> {
                        ProductImgModel productImgModel = base.convertEntityToDto(e, new ProductImgModel());
                        //图片类型：商品详情图
                        productImgModel = productImgService.insertProductImage(ProductConstant.ImgTypeEnum.BANNER, saveProductInfoModel,
                                productImgModel, userSession);
                        //以Id判断是否构建成功
                        if (productImgModel.getId() == null) {
                            //TODO 异常构建 全局回滚
                            throw new RuntimeException(ProductErrorEnum.PRODUCT_IMG_CREATE_ERROR.getMsg());
                        } else {
                            //收集banner图片ID集合
                            imgStringIds.add(String.valueOf(productImgModel.getId()));
                        }
                    }
            );
        } else {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品banner图片不能为空!");
        }
        //添加商品详情信息
        List<ProductImgDto> productImgDto = productInfoDto.getProductImgDtoList();
        if (!CollectionUtils.isEmpty(productImgDto)) {
            //删除之前的图片信息
            productImgService.updateProductImage(ProductConstant.ImgTypeEnum.DETAILS, saveProductInfoModel);
            productImgDto.stream().forEach(
                    e -> {
                        ProductImgModel productImgModel = base.convertEntityToDto(e, new ProductImgModel());
                        //图片类型：商品详情图
                        productImgModel = productImgService.insertProductImage(ProductConstant.ImgTypeEnum.DETAILS, saveProductInfoModel,
                                productImgModel, userSession);
                        //以Id判断是否构建成功
                        if (productImgModel.getId() == null) {
                            //TODO 异常构建 全局回滚
                            throw new RuntimeException(ProductErrorEnum.PRODUCT_IMG_CREATE_ERROR.getMsg());
                        }
                    }
            );
        }
        // 判断商品是否设置自动下架
        if (productInfoDto.getIstaskLowerShelf()) { // 自动下架
            // 如果设置了自动下架，获取自动下架时间
//            Date lowerShelfTime = DateUtils.parseDateMilliFormat(productInfoDto.getLowerShelfTimeStr());
            Date lowerShelfTime = productInfoDto.getLowerShelfTime();
            productTaskLowerShelfService.updateProductLowerShelfTime(lowerShelfTime, saveProductInfoModel.getId());
        } else { // 没有设置自动下架
            productTaskLowerShelfService.updateProductLowerShelfDel(saveProductInfoModel.getId());
        }
        //更新
        return new DataOutput(productInfoDtoResult);

    }

    /**
     * 产品相关数据处理
     *
     * @param productInfoDto
     * @return
     */
    private DataOutput productData(ProductAddDto productInfoDto) {
        final long salesPrice = 500000L;//默认限定价格
        //补充商品分类名
        if (productInfoDto == null) {
            return base.getBadErrorMsg("传递参数不能为空!");
        }
        if (productInfoDto.getCategoryId() != null) {
            BaseProductCategoryModel baseProductCategoryModel = baseProductCategoryService.BaseProductCategoryById(productInfoDto.getCategoryId());
            if (baseProductCategoryModel != null) {
                productInfoDto.setCategoryName(baseProductCategoryModel.getCategoryName());
            }
        } else {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品基础分类信息不能为空!");
        }
        //补充品牌名称
        if (productInfoDto.getBrandCode() != null) {
            ProductBrandModel productBrandModel = productBrandServices.findProductBrandByCode(productInfoDto.getBrandCode());
            if (productBrandModel != null) {
                productInfoDto.setBrandName(productBrandModel.getCnName());
                productInfoDto.setBrandEnName(productBrandModel.getEnName());
            }
        } else {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品品牌信息不能为空!");
        }
        //表情包处理
        if (StringUtils.isEmpty(productInfoDto.getProductName())) {
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品名不能为空!");
        } else {
            productInfoDto.setProductName(EmojiUtils.EmojiFilter(productInfoDto.getProductName()));
        }
        if (!StringUtils.isEmpty(productInfoDto.getProductDetail())) {
            productInfoDto.setProductDetail(EmojiUtils.EmojiFilter(productInfoDto.getProductDetail()));
        }
        if (!StringUtils.isEmpty(productInfoDto.getProductDescription())) {
            productInfoDto.setProductDescription(EmojiUtils.EmojiFilter(productInfoDto.getProductDescription()));
        }
        if (!StringUtils.isEmpty(productInfoDto.getProductAssembleDesc())){
          int result =  StringDealUtils.getCount(productInfoDto.getProductAssembleDesc(),"？");
            if (result==1){
                productInfoDto.setProductAssembleDesc(EmojiUtils.EmojiFilter(productInfoDto.getProductAssembleDesc()));
            }else if (result<1){
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "显示总库存字段，需包含中文？号");
            }else{
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "显示总库存字段，只能包含一个中文？号");
            }
        }
        //运营类目数据并不能为空
        List<Long> operation = new ArrayList<>();
        if (CollectionUtils.isEmpty(productInfoDto.getOperationCategoryIds())) {
            return base.getBadErrorMsg("运营类目不能为空!");
        } else {
            for (int i = 0; i < productInfoDto.getOperationCategoryIds().size(); i++) {
                if (operation.contains(productInfoDto.getOperationCategoryIds().get(i))) {
                    return base.getBadErrorMsg("请勿选择重复的运营类目!");
                } else {
                    operation.add(productInfoDto.getOperationCategoryIds().get(i));
                }
            }

        }
        //判断主图信息
        if (StringUtils.isEmpty(productInfoDto.getProductMainImgUrl())) {
            if (productInfoDto.getProductBannerImgDtoList() != null && productInfoDto.getProductBannerImgDtoList().size() > 0) {
                if (!StringUtils.isEmpty(productInfoDto.getProductBannerImgDtoList().get(0).getImageUrl())) {
                    productInfoDto.setProductMainImgUrl(productInfoDto.getProductBannerImgDtoList().get(0).getImageUrl());
                } else {
                    return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品BANNER图不能为空!");
                }
            } else {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品BANNER图不能为空!");
            }
        }
        if (productInfoDto.getSalesPrice() == null) {//商品价格判断
            return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品售价不能为空!");
        } else {
            if (productInfoDto.getSalesPrice() > salesPrice) {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "售价不能超过5000元!");
            }
        }
        if (productInfoDto.getWholesalePrice() == null) {
            productInfoDto.setWholesalePrice(0L);
        }
        if (productInfoDto.getMarkerPrice() == null) {
            productInfoDto.setMarkerPrice(0L);
        }
        //排序值判断
        if (productInfoDto.getProductSort() == null) {
            productInfoDto.setProductSort(0);
        }
        return new DataOutput(CommonStatus.SUCCESS);
    }

    /**
     * 查询产品基本信息
     *
     * @param productId
     * @return
     */
    public ProductInfoModel getProductInfoById(Long productId) {
        return queryFactory.select(Q).from(Q).where(Q.id.eq(productId)).fetchOne();
    }

    /**
     * 产品列表信息
     *
     * @param productName
     * @param staDate
     * @param endDate
     * @param categoryId
     * @param isSale
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PagedOutput<ProductInfoVo> findProductInfoList(HttpServletRequest request, String productName, String staDate, String endDate, Long categoryId, Integer isSale, Integer pageNo, Integer pageSize, String productCode) {
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        logger.info("产品查询列表传递参数:productName:{},staDate:{},endDate:{},categoryId{},isSale:{}", productName, staDate, endDate, categoryId, isSale);
        logger.info("开始查询:{}", DateUtils.getDateSecondFormat());
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new PagedOutput<>(pagedInput, 0, null);
        }
        List<ProductInfoVo> productInfoDtoList = null;
        Date staDate1 = null;
        Date endDate1 = null;
        if (!StringUtils.isEmpty(staDate) && !StringUtils.isEmpty(endDate)) {
            staDate1 = DateUtils.parseDateMilliFormat(staDate + " 00:00:00"); // 格式化日期
            endDate1 = DateUtils.parseDateMilliFormat(endDate + " 23:59:59"); // 格式化日期
        }
        PagedOutput<ProductInfoModel> pagedOutput = null;
        //组装基础分类条件
        /*List<Long> categoryIdList = null;
        if (categoryId != null) {
            categoryIdList = productCmsCategoryService.findCategoryListByParentCategoryId(categoryId);
        }*/

        //判断销售状态
        final Date staDate2 = staDate1;
        final Date endDate2 = endDate1;
        logger.info("开始主表查询:{}", DateUtils.getDateSecondFormat());
        PredicateBuilder predicateBuilder = PredicateBuilder.conjunction()
                .ifNotNullThenAnd(userSession.getShopId(), () -> Q.shopId.eq(userSession.getShopId()))
                .ifHasTextThenAnd(productCode, () -> Q.productCode.like("%" + productCode + "%"))
                .ifHasTextThenAnd(productName, () -> Q.productName.like("%" + productName + "%"))
                .ifNotNullThenAnd(staDate2, () -> Q.createTime.between(staDate2, endDate2))
                .ifNotNullThenAnd(categoryId, () -> Q.categoryId.eq(categoryId))
                .and(() -> Q.isDelete.eq(false));
        if (isSale != null && 0 == isSale) {
            pagedOutput = repository.pagingList(predicateBuilder
                    .ifNotNullThenAnd(isSale, () -> Q.isSale.eq(false))
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.productSort), new OrderSpecifier<>(Order.DESC, Q.lastUpdateTime));
        } else if (isSale != null && 1 == isSale) {
            pagedOutput = repository.pagingList(predicateBuilder
                    .ifNotNullThenAnd(isSale, () -> Q.isSale.eq(true))
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.productSort), new OrderSpecifier<>(Order.DESC, Q.lastUpdateTime));
        } else {
            pagedOutput = repository.pagingList(predicateBuilder
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.productSort), new OrderSpecifier<>(Order.DESC, Q.lastUpdateTime));
        }

        try {
            logger.info("开始补充数据:{}", DateUtils.getDateSecondFormat());
            productInfoDtoList = pagedOutput.getData().stream().map(
                    it -> {
                        ProductInfoVo productInfoVo = new ProductInfoVo();
                        BeanUtils.copyProperties(it, productInfoVo);
                        //补充图片
                       /* List<BaseImgDto> productImgDtoList = productImgService.findImageByProductIdAndType(it.getId(), ProductConstant.ImgTypeEnum.DETAILS);
                        if (productImgDtoList != null) {
                            productInfoVo.setProductImgDtoList(productImgDtoList);
                        }*/
                      /*  //补充商品详情图
                        productInfoVo.setProductDetailImgUrl(productImgService.findProductImageByProductIdAndImgType(it.getId(), ProductConstant.ProductImgType.MAIN_PRODUCT_DETAIL));*/
                        //补充图片
                       /* List<BaseImgDto> productBannerImgDtoList = productImgService.findImageByProductIdAndType(it.getId(), ProductConstant.ImgTypeEnum.BANNER);
                        if (productBannerImgDtoList != null) {
                            productInfoVo.setProductBannerImgDtoList(productBannerImgDtoList);
                        }*/
                        //统计库存
                        Long stockCount = productCmsSkuService.entityStockCountByProductId(it.getId());
                        productInfoVo.setInventory(stockCount);
                        //补充用户名
                        /*if (it.getCreateBy() != null) {
                            OperationUserCmsModel operationUserCmsModel = operationUserService.findUserInfoById(it.getCreateBy());
                            if (operationUserCmsModel != null) {
                                productInfoVo.setCreateByName(operationUserCmsModel.getUserName());
                            }
                        }*/
                        return productInfoVo;
                    }
            ).collect(Collectors.toList());
            logger.info("补充数据结束:{}", DateUtils.getDateSecondFormat());
        } catch (Exception e) {
            logger.info("产品数据列表循环请求异常");
            e.printStackTrace();
        }
        return new PagedOutput<>(pagedInput, pagedOutput.getTotalElements(), productInfoDtoList);
    }

    /**
     * 数据导出
     *
     * @param request
     * @param response
     * @param productName
     * @param
     * @param categoryId
     * @param isSale
     */
    public void findProductInfoExport(HttpServletRequest request, HttpServletResponse response,
                                      String productName, String staDate, String endDate, Long categoryId, Integer isSale
    ) {
        String productCode = null;
        Integer pageNo = 1;
        Integer pageSize = Integer.MAX_VALUE;
        PagedOutput<ProductInfoVo> productInfoVoPagedOutput = findProductInfoList(request, DataUtils.Decoder(productName), staDate, endDate, categoryId, isSale, pageNo, pageSize, productCode);
        //处理数据
        JSONArray jsonArray = new JSONArray();
        jsonArray.fluentAddAll(productInfoVoPagedOutput.getData());
        String fileName = "商品列表数据" + DateUtils.nowDate("yyyyMMddHHmmss") + ".xlsx";
        String sheetName = "sheet1";
        try {
            this.setResponseHeader(request, response, fileName);
            OutputStream os = response.getOutputStream();
            ExcelConverter excelConverter = ExcelConverter.forXlsx();
            DataTable dataTable = new DataTable(sheetName);
            List<DataColumn> columns = new ArrayList<>();
            columns.add(new DataColumn("productCode", "商品编号"));
            columns.add(new DataColumn("productName", "商品名"));
            columns.add(new DataColumn("salesPrice", "售价"));
            columns.add(new DataColumn("salesCount", "销量"));
            columns.add(new DataColumn("inventory", "库存"));
            columns.add(new DataColumn("categoryName", "所属类目"));
            columns.add(new DataColumn("createTimeString", "创建时间"));
            columns.add(new DataColumn("createByName", "创建人"));
            dataTable.addColumns(columns);
            excelConverter.export(os, dataTable, jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     *
     * @param request
     * @param response
     * @param fileName
     */
    private void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel"); // 保存为excel
            response.setHeader("Content-Disposition", "attachment;" + ExcelExportUtil.getFileName(request, fileName));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 删除商品信息
     *
     * @param productId
     * @return
     */
    @Transactional
    public DataOutput deleteProductById(HttpServletRequest request, String productId) {
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null || userSession.getId() == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        logger.info("删除商品参数:{}", productId);
        try {
            if (productId != null) {
                ProductInfoModel productInfoModel1 = repository.findOne(Q.id.eq(Long.valueOf(productId)));
                if (productInfoModel1 != null && productInfoModel1.getIsSale() == true) {
                    return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), "商品未下架不能删除，请先下架!");
                }
                repository.updateByWhere(Q.id.eq(Long.valueOf(productId)),
                        it -> it.set(Q.isDelete, true)
                                .set(Q.lastUpdateBy, userSession.getId())
                                .set(Q.lastUpdateTime, new Date()));
                //删除Es中相关数据
                productRepository.deleteById(Long.valueOf(productId));
                cmsProductGroupActivityService.deleteProductGroupActivityActivityStatesByProductId(Long.valueOf(productId));
                return new DataOutput(CommonStatus.SUCCESS);

            } else {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "商品ID不能为空,请重新输入!");
            }
        } catch (Exception e) {
            logger.error("删除:{}产品信息失败:{}", productId, e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), CommonStatus.SERVER_ERROR.getMessage(), e.getMessage());
        }
    }

    /**
     * 上下架商品信息
     *
     * @param productId
     * @param saleType
     * @return
     */
    @Transactional
    public DataOutput updateProductSaleById(HttpServletRequest request, String productId, Boolean saleType) {
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null || userSession.getId() == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        logger.info("商品上/下架:商品ID{},状态:{}", productId, saleType);
        try {
            if (!StringUtils.isEmpty(productId) && saleType != null) {
                Date date = new Date();
                ProductInfoModel productInfoModel = queryFactory.select(Q).from(Q).where(Q.id.eq(Long.valueOf(productId)).and(Q.isDelete.eq(false))).fetchFirst();
                productInfoModel.setIsSale(saleType);
                productInfoModel.setLastUpdateTime(date);
                if (productInfoModel != null) {
                    Integer result = repository.updateByWhere(Q.id.eq(Long.valueOf(productId)),
                            it -> it.set(Q.isSale, productInfoModel.getSale())
                                    .set(Q.lastUpdateBy, userSession.getId())
                                    .set(Q.lastUpdateTime, date));
                    logger.info("当前时间:{}", date);
                    if (result > 0) {
                        productCmsSkuService.updateProductSkuIsSale(Long.valueOf(productId), saleType);
                        if (true == saleType) {//上架就新增ES数据
                            if (productInfoModel != null) {
                                productRepository.save(base.convertEntityToDto(productInfoModel,
                                        new ProductInfoModelForSearch()));
                            }
                        } else {//下架就删除ES数据
                            productRepository.deleteById(Long.valueOf(productId));
                            cmsProductGroupActivityService.updateProductGroupActivityActivityStatesByProductId(Long.valueOf(productId));
                        }
                        return new DataOutput(CommonStatus.SUCCESS);
                    } else {
                        return new DataOutput(CommonStatus.SERVER_ERROR);
                    }
                } else {
                    return base.getErrorMsg("未查询到相关产品信息!");
                }
            } else {
                return new DataOutput(CommonStatus.BAD_REQUEST.getCode(), "输入参数有误!");
            }
        } catch (Exception e) {
            logger.error("上下架:{}产品信息失败:{}", productId, e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), CommonStatus.SERVER_ERROR.getMessage(), e.getMessage());
        }
    }

    /**
     * 根据产品ID查询产品详情
     *
     * @param productId
     * @return
     */
    public DataOutput<ProductInfoVo> findProductInfoById(Long productId) {
        if (productId != null) {
            List<ProductInfoVo> productInfoDtos = repository.findAll(Q.id.eq(productId)).stream().
                    map(it -> {
                                ProductInfoVo productInfoDto1 = new ProductInfoVo();
                                BeanUtils.copyProperties(it, productInfoDto1);
                                //补充基础分类
                                Long parentId = productCategoryService.findParentCategoryId(productInfoDto1.getCategoryId());
                                if (parentId != null) {
                                    productInfoDto1.setParentCategoryId(parentId);
                                    Long parentParentId = productCategoryService.findParentCategoryId(parentId);
                                    if (parentParentId != null) {
                                        productInfoDto1.setParentParentCategoryId(parentParentId);
                                    }
                                }
                                //补充运营分类
                                List<ProductCategoryRelationModel> productCategoryRelationModelList = productCategoryRelationService.findProductCategoryRelationByProductId(it.getId());
                                List<ProductOperationCategoryVo> list = new ArrayList<>();
                                if (!CollectionUtils.isEmpty(productCategoryRelationModelList)) {
                                    list = productCategoryRelationModelList.stream().map(is -> {
                                        ProductOperationCategoryVo productOperationCategoryVo = new ProductOperationCategoryVo();
                                        OperationProductCategoryModel operationProductCategoryModel = operationProductCategoryService.findProductCategoryByCategoryId(is.getCategoryId());
                                        if (operationProductCategoryModel != null) {
                                            productOperationCategoryVo.setOperationCategoryId(operationProductCategoryModel.getId());
                                            if (operationProductCategoryModel.getParentId() == 0L) {
                                                productOperationCategoryVo.setParentOperationCategoryId(operationProductCategoryModel.getId());
                                            } else {
                                                productOperationCategoryVo.setParentOperationCategoryId(operationProductCategoryModel.getParentId());
                                            }
                                        }
                                        return productOperationCategoryVo;
                                    }).collect(Collectors.toList());

                                } else {
                                    list.add(new ProductOperationCategoryVo());
                                }
                                productInfoDto1.setProductOperationCategoryVoList(list);

                                //第三步信息补充
                                List<ProductSpecificationDto> productSpecificationDtos = productSpecificationService.getProductSpecificationListByProductId(productId);
                                if (productSpecificationDtos != null) {
                                    productInfoDto1.setProductSpecificationDtoList(productSpecificationDtos);
                                }
                                //添加关联的URL
                                ProductLogisticsInfoModel productLogisticsInfoModel = productLogisticsInfoService.findProductLogisticsById(it.getId());
                                if (productLogisticsInfoModel != null) {
                                    productInfoDto1.setRelevantUrl(productLogisticsInfoModel.getRelevantUrl());
                                }
                                //产品库存描述
                                String relevanceInfo = productRelevanceInfoService.findRelevanceInfoByProductId(it.getId(), ProductRelevanceInfoEnums.TYPE.PRODUCT_ASSEMBLE_DESC);
                                if (!StringUtils.isEmpty(relevanceInfo)) {
                                    productInfoDto1.setProductAssembleDesc(relevanceInfo);
                                }
                                List<BaseImgDto> productBannerImgDtoList = productImgService.findImageByProductIdAndType(it.getId(), ProductConstant.ImgTypeEnum.BANNER);
                                if (productBannerImgDtoList != null) {
                                    productInfoDto1.setProductBannerImgDtoList(productBannerImgDtoList);
                                }
                                List<BaseImgDto> productDetailList = productImgService.findImageByProductIdAndType(it.getId(), ProductConstant.ImgTypeEnum.DETAILS);
                                if (productBannerImgDtoList != null) {
                                    productInfoDto1.setProductImgDtoList(productDetailList);
                                }
                                // 获取这个商品是否为定时上下架，如果该商品有多条，返回最新的一条(未下架或已下架情况下按下架时间倒序拿第一条)
                                ProductTaskLowerShelfModel productaskLowerShelfModel = productTaskLowerShelfService.findTaskLowerDetailByProductId(it.getId());
                                // 如果productaskLowerShelfModel不为空，获取下架时间
                                if (productaskLowerShelfModel != null) {
                                    productInfoDto1.setLowerShelfTime(productaskLowerShelfModel.getLowerShelfTime());
                                    productInfoDto1.setLowerShelfTimeStr(DateUtils.getDateSecondFormat(productaskLowerShelfModel.getLowerShelfTime()));
                                    // 如果有记录，但是不为未执行，统一设置字段为不是自动下架
                                    if (ProductConstant.EXECUTED_TASK_ENUM.UNEXECUTED.getCode().equals(productaskLowerShelfModel.getIsExecuted())) {
                                        productInfoDto1.setIstaskLowerShelf(1); // 是自动下架
                                    } else {
                                        productInfoDto1.setIstaskLowerShelf(0); // 不是自动下架
                                    }
                                } else {
                                    productInfoDto1.setIstaskLowerShelf(0); // 不是自动下架
                                }
                                return productInfoDto1;
                            }
                    ).collect(Collectors.toList());
            if (productInfoDtos.size() > 0) {
                return base.getSuccessMsg(productInfoDtos.get(0));
            }
        }
        return base.getBadErrorMsg();

    }

    /**
     * 根据产品Code查询产品详情
     *
     * @param productCode
     * @return
     */
    public DataOutput<ProductInfoVo> findProductInfoByCode(String productCode) {
        ProductInfoDto productInfoDto = null;
        if (!StringUtils.isEmpty(productCode)) {
            List<ProductInfoVo> productInfoDtos = repository.findAll(Q.productCode.eq(productCode)).stream().
                    map(it -> {
                                ProductInfoVo productInfoDto1 = new ProductInfoVo();
                                BeanUtils.copyProperties(it, productInfoDto1);
                                //补充运营分类
                                List<ProductCategoryRelationModel> productCategoryRelationModelList = productCategoryRelationService.findProductCategoryRelationByProductId(it.getId());
                                List<ProductOperationCategoryVo> list = new ArrayList<>();
                                if (!CollectionUtils.isEmpty(productCategoryRelationModelList)) {
                                    list = productCategoryRelationModelList.stream().map(is -> {
                                        ProductOperationCategoryVo productOperationCategoryVo = new ProductOperationCategoryVo();
                                        OperationProductCategoryModel operationProductCategoryModel = operationProductCategoryService.findProductCategoryByCategoryId(is.getCategoryId());
                                        if (operationProductCategoryModel != null) {
                                            productOperationCategoryVo.setOperationCategoryId(operationProductCategoryModel.getId());
                                            if (operationProductCategoryModel.getParentId() == 0L) {
                                                productOperationCategoryVo.setParentOperationCategoryId(operationProductCategoryModel.getId());
                                            } else {
                                                productOperationCategoryVo.setParentOperationCategoryId(operationProductCategoryModel.getParentId());
                                            }
                                        }
                                        return productOperationCategoryVo;
                                    }).collect(Collectors.toList());
                                    productInfoDto1.setProductOperationCategoryVoList(list);
                                } else {
                                    list.add(new ProductOperationCategoryVo());
                                }
                                productInfoDto1.setProductOperationCategoryVoList(list);
                                //添加关联的URL
                                ProductLogisticsInfoModel productLogisticsInfoModel = productLogisticsInfoService.findProductLogisticsById(it.getId());
                                if (productLogisticsInfoModel != null) {
                                    productInfoDto1.setRelevantUrl(productLogisticsInfoModel.getRelevantUrl());
                                }
                                //产品库存描述
                                String relevanceInfo = productRelevanceInfoService.findRelevanceInfoByProductId(it.getId(), ProductRelevanceInfoEnums.TYPE.PRODUCT_ASSEMBLE_DESC);
                                if (!StringUtils.isEmpty(relevanceInfo)) {
                                    productInfoDto1.setProductAssembleDesc(relevanceInfo);
                                }
                                List<BaseImgDto> productBannerImgDtoList = productImgService.findImageByProductIdAndType(Long.valueOf(it.getId()), ProductConstant.ImgTypeEnum.BANNER);
                                if (productBannerImgDtoList != null) {
                                    productInfoDto1.setProductBannerImgDtoList(productBannerImgDtoList);
                                }
                                List<BaseImgDto> productDetailList = productImgService.findImageByProductIdAndType(Long.valueOf(it.getId()), ProductConstant.ImgTypeEnum.DETAILS);
                                if (productBannerImgDtoList != null) {
                                    productInfoDto1.setProductImgDtoList(productDetailList);
                                }
                                return productInfoDto1;
                            }
                    ).collect(Collectors.toList());
            if (productInfoDtos.size() > 0) {
                return new DataOutput(productInfoDtos.get(0));
            }
        }
        return new DataOutput(productInfoDto);

    }

    /**
     * 商品批量上下架
     *
     * @param request
     * @param productSaleChangeDto
     * @return
     */
    @Transactional
    public DataOutput updateSaleStatusByIds(HttpServletRequest request, ProductSaleChangeDto productSaleChangeDto) {
        OperationUserCmsModel operationUserCmsModel = UserSession.getUserSession(request);
        if (operationUserCmsModel == null) {
            return base.getBadErrorMsg("未获取到用户信息，请重新登录!");
        }
        logger.info("批量上下架参数:{}", JSON.toJSONString(productSaleChangeDto));
        if (productSaleChangeDto != null && !CollectionUtils.isEmpty(productSaleChangeDto.getProductIds()) && productSaleChangeDto.getSaleStatus() != null) {
            if (productSaleChangeDto.getSaleStatus().equals(false)) {//下架商品
                Integer result = repository.updateByWhere(Q.id.in(productSaleChangeDto.getProductIds()).and(Q.isDelete.eq(false)),
                        it -> it.set(Q.isSale, false)
                                .set(Q.lastUpdateBy, operationUserCmsModel.getId())
                                .set(Q.lastUpdateTime, new Date()));
                if (result > 0) {
                    productCmsSkuService.updateProductIdsSkuIsSale(productSaleChangeDto.getProductIds(), productSaleChangeDto.getSaleStatus());
                    for (Long productId : productSaleChangeDto.getProductIds()) {
                        productRepository.deleteById(productId);
                        cmsProductGroupActivityService.updateProductGroupActivityActivityStatesByProductId(productId);
                    }
                    return base.getSuccessMsg(result);
                } else {
                    return base.getErrorMsg("批量下架商品失败，请重新操作!");
                }
            } else {//上架(先判断商品的价格和库存，再执行上架操作!)
                //主信息售价判断
                List<ProductInfoModel> productInfoModelList = repository.findAll(Q.id.in(productSaleChangeDto.getProductIds()).and(Q.isDelete.eq(false)));
                if (productInfoModelList != null && productInfoModelList.size() > 0) {
                    for (ProductInfoModel productInfoModel : productInfoModelList) {
                        if (productInfoModel.getSalesPrice() <= 0) {
                            return base.getBadErrorMsg("产品:" + productInfoModel.getId() + "," + productInfoModel.getProductName() + "售价:" + productInfoModel.getSalesPrice() + ",不可上架!");
                        }
                    }
                } else {
                    return base.getBadErrorMsg("未查询到商品主信息，请确认参数是否有误!");
                }
                //sku售价库存判断
                List<ProductSkuModel> productSkuModelSubsetList = productCmsSkuService.findSubsetProductSkuList(productSaleChangeDto.getProductIds());
                if (productSkuModelSubsetList != null && productSkuModelSubsetList.size() > 0) {
                    for (ProductSkuModel productSkuModel : productSkuModelSubsetList) {
                        if (productSkuModel.getSalesPrice() <= 0L || productSkuModel.getEntityStock() <= 0L) {
                            return base.getBadErrorMsg("产品:" + productSkuModel.getProductId() + ",sku:" + productSkuModel.getId() + ",售价:" + productSkuModel.getSalesPrice() + ",库存:" + productSkuModel.getEntityStock() + ",不可上架!");
                        }
                    }
                } else {
                    return base.getBadErrorMsg("未查询到sku信息，请确认参数是否有误!");
                }
                //执行上架操作
                Integer result = repository.updateByWhere(Q.id.in(productSaleChangeDto.getProductIds()).and(Q.isDelete.eq(false)), it -> it.set(Q.isSale, true)
                        .set(Q.lastUpdateBy, operationUserCmsModel.getId())
                        .set(Q.lastUpdateTime, new Date()));
                if (result > 0) {
                    productCmsSkuService.updateProductIdsSkuIsSale(productSaleChangeDto.getProductIds(), productSaleChangeDto.getSaleStatus());
                    for (ProductInfoModel productInfoModel : productInfoModelList) {
                        productRepository.save(base.convertEntityToDto(productInfoModel,
                                new ProductInfoModelForSearch()));
                    }
                    return base.getSuccessMsg(result);
                } else {
                    return base.getErrorMsg("批量上架商品失败，请重新操作!");
                }
            }


        } else {
            return base.getBadErrorMsg("参数有误,请重新提交!");
        }


    }

    /**
     * 功能描述: 根据商品id获取商品
     *
     * @param ids 商品id列表
     * @return
     * @auther: Kien
     * @date: 2019/6/27 17:07
     */
    public List<ProductInfoModel> getProductByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        return repository.findAll(PredicateBuilder.conjunction().and(() -> Q.id.in(ids)).get());
    }

    /**
     * 功能描述: 批量修改商品下架
     *
     * @param productIds 商品id列表
     * @param date       操作时间
     * @return
     * @auther: Kien
     * @date: 2019/6/28 9:54
     */
    @Transactional
    public int updateProductSaleByIds(List<Long> productIds, Date date) {
        int i = 0;
        if (CollectionUtils.isEmpty(productIds)) {
            return i;
        }
        i = repository.updateByWhere(PredicateBuilder.conjunction()
                        .and(() -> Q.id.in(productIds)).get(),
                it -> {
                    it.set(Q.isSale, false);
                    it.set(Q.lastUpdateTime, date);
                });
        // 修改这个商品的所有子sku
        if (i != 0) {
            productCmsSkuService.updateProductIdsSkuIsSale(productIds, false);
        }
        return i;
    }

    /**
     * 修改商品名及商品规格信息
     *
     * @param request
     * @param productNameAndSkuDto
     * @return
     */
    @Transactional
    public DataOutput updateProductNameAndSku(HttpServletRequest request, ProductNameAndSkuDto productNameAndSkuDto) {
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        logger.info("修改商品规格:{}", JSON.toJSONString(productNameAndSkuDto));
        //参数校验
        if (productNameAndSkuDto != null) {
            if (productNameAndSkuDto.getProductId() == null || StringUtils.isEmpty(productNameAndSkuDto.getProductName())) {
                return base.getBadErrorMsg("商品id或商品名不能为空!");
            } else {
                productNameAndSkuDto.setProductName(EmojiUtils.EmojiFilter(productNameAndSkuDto.getProductName()));
            }
            if (!CollectionUtils.isEmpty(productNameAndSkuDto.getProductSkuUpdateDtoList())) {
                for (ProductSkuUpdateDto productSkuUpdateDto : productNameAndSkuDto.getProductSkuUpdateDtoList()) {
                    if (productSkuUpdateDto.getProductSkuId() == null || productSkuUpdateDto.getSalesPrice() == null || productSkuUpdateDto.getEntityStock() == null) {
                        return base.getBadErrorMsg("商品sku相关信息不能为空!");
                    }
                    if (productSkuUpdateDto.getSalesPrice() == 0) {
                        return base.getBadErrorMsg("商品sku售价不能为0!");
                    }
                    if (productSkuUpdateDto.getEntityStock() == null) {
                        return base.getBadErrorMsg("商品sku库存不能为空!");
                    }
                }
            }

        } else {
            return base.getBadErrorMsg();
        }

        //判断商品信息是否存在
        ProductInfoModel productInfoModel = queryFactory.select(Q).from(Q).where(Q.id.eq(productNameAndSkuDto.getProductId()).and(Q.isDelete.eq(false))).fetchFirst();
        if (productInfoModel != null) {
            try {
                //修改主信息
                int result = repository.updateByWhere(Q.id.eq(productNameAndSkuDto.getProductId()),
                        it -> it.set(Q.productName, productNameAndSkuDto.getProductName())
                                .set(Q.lastUpdateBy, userSession.getId())
                                .set(Q.lastUpdateTime, new Date()));
                if (result > 0) {
                    //商品主信息新增成功 则同步数据至ES
                    productInfoModel.setProductName(productNameAndSkuDto.getProductName());
                    productRepository.save(base.convertEntityToDto(productInfoModel,
                            new ProductInfoModelForSearch()));
                    //修改sku信息
                    if (!CollectionUtils.isEmpty(productNameAndSkuDto.getProductSkuUpdateDtoList())) {
                        productCmsSkuService.updateProductSku(productNameAndSkuDto.getProductSkuUpdateDtoList());
                    }
                    return base.getSuccessMsg();
                } else {
                    return base.getErrorMsg("商品修改信息失败!");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return new DataOutput(CommonStatus.SERVER_ERROR.getCode(), CommonStatus.SERVER_ERROR.getMessage());
        } else {
            return base.getBadErrorMsg("商品信息不存在!");
        }

    }


    /**
     * 根据产品id批量删除产品
     *
     * @param request
     * @param productIdList
     * @return
     */
    @Transactional
    public DataOutput deleteProductByIdS(HttpServletRequest request, List<Long> productIdList) {
        //验证登陆信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        logger.info("批量删除商品:{}", productIdList);
        //参数校验
        if (!CollectionUtils.isEmpty(productIdList)) {
            for (Long productId : productIdList) {
                ProductInfoModel productInfoModel = queryFactory.select(Q).from(Q).where(Q.id.eq(productId).and(Q.isDelete.eq(false))).fetchFirst();
                if (productInfoModel == null) {
                    return base.getErrorMsg("商品Id:" + productId + "参数有误!");
                } else {
                    if (productInfoModel.getSale().equals(true)) {
                        return base.getErrorMsg("上架商品不支持删除操作，请先下架商品");
                    }
                }
            }

        } else {
            return base.getErrorMsg();
        }
        int result = repository.updateByWhere(Q.id.in(productIdList),
                it -> it.set(Q.isDelete, true)
                        .set(Q.lastUpdateBy, userSession.getId())
                        .set(Q.lastUpdateTime, new Date()));
        if (result > 0) {
            int esResult = productRepository.deleteAllByIdIn(productIdList);
            System.out.println(esResult);
        }
        return base.getSuccessMsg();

    }

    public DataOutput updateEs(Integer idMin, Integer idMnx, Boolean sale) {
        List<ProductInfoModel> list = queryFactory.select(Q).from(Q)
                .where(Q.id.between(idMin, idMnx).and(Q.isDelete.eq(false)).and(Q.isSale.eq(sale))).fetch();
        if (list != null && list.size() > 0) {
            for (ProductInfoModel productInfoModel : list) {
                productRepository.deleteById(productInfoModel.getId());
                ProductInfoModelForSearch productInfoModelForSearch = productRepository.save(base.convertEntityToDto(productInfoModel,
                        new ProductInfoModelForSearch()));
                logger.info("同步商品数据:{}", JSON.toJSONString(productInfoModelForSearch));
            }
        }
        return base.getSuccessMsg();
    }

    /**
     * 修改商品排序值
     *
     * @param request
     * @param productId
     * @param productSort
     * @return
     */
    @Transactional
    public DataOutput updateProductSortById(HttpServletRequest request, Long productId, Integer productSort) {
        //验证登陆信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null || userSession.getId() == null || userSession.getShopId() == null) {
            return base.getErrorMsg("用户未登录或未绑定门店信息!");
        }
        Date date = new Date();
        ProductInfoModel productInfoModel = queryFactory.select(Q).from(Q).where(Q.id.eq(productId).and(Q.shopId.eq(userSession.getShopId()))).fetchFirst();
        if (productInfoModel == null || productInfoModel.getId() == null) {
            return base.getSuccessMsg("未查询到商品相关信息，请确认数据是否有误!");
        } else {
            repository.updateByWhere(Q.id.eq(productId).and(Q.shopId.eq(userSession.getShopId())),
                    it -> it.set(Q.productSort, productSort)
                            .set(Q.lastUpdateBy, userSession.getId())
                            .set(Q.lastUpdateTime, date));
            productInfoModel.setProductSort(productSort);
            productInfoModel.setLastUpdateBy(userSession.getId());
            productInfoModel.setLastUpdateTime(date);
            //更新ES
            ProductInfoModelForSearch productInfoModelForSearch = productRepository.save(base.convertEntityToDto(productInfoModel,
                    new ProductInfoModelForSearch()));
            return base.getSuccessMsg(productInfoModelForSearch);
        }

    }

    /**
     * @param request
     * @param productId
     * @param productName
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PagedOutput<CashCouponsProductListDto> findCashCouponsProductInfoList(HttpServletRequest request, Long operationCategoryId, Long productId, String productName, Integer pageNo, Integer pageSize) {
        PagedInput pagedInput = new PagedInput(pageSize, pageNo);
        logger.info("产品查询列表传递参数:productId:{},productName:{}", productId, productName);
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new PagedOutput<>(pagedInput, 0, null);
        }
        //运营分类关联的产品id
        List<Long> productIdS = new ArrayList<>();
        if (operationCategoryId != null) {
            productIdS = productCategoryRelationService.findProductIdsByCategoryId(operationCategoryId);
            if (CollectionUtils.isEmpty(productIdS)) {//运营分类没有关联产品时确保查不到产品
                productIdS.add(0L);
            }
        }
        List<Long> productIdList = productIdS;
        PagedOutput<ProductInfoModel> pagedOutput = repository.pagingList(PredicateBuilder.conjunction()
                .ifNotNullThenAnd(productId, () -> Q.id.eq(productId))
                .ifNotEmptyThenAnd(productIdList, () -> Q.id.in(productIdList))
                .ifHasTextThenAnd(productName, () -> Q.productName.like("%" + productName + "%"))
                .and(() -> Q.shopId.eq(userSession.getShopId()))
                .and(() -> Q.isSale.eq(true))
                .and(() -> Q.isDelete.eq(false))
                .get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.lastUpdateTime));

        List<CashCouponsProductListDto> list = pagedOutput.getData().stream().map(it -> {
            CashCouponsProductListDto cashCouponsProductListDto = new CashCouponsProductListDto();
            BeanUtils.copyProperties(it, cashCouponsProductListDto);
            //统计库存
            Long stockCount = productCmsSkuService.entityStockCountByProductId(cashCouponsProductListDto.getId());
            cashCouponsProductListDto.setInventory(stockCount);
            //添加最低价
            Long salePrice = productCmsSkuService.getSalePriceMin(cashCouponsProductListDto.getId());
            cashCouponsProductListDto.setSalesPrice(salePrice);
            return cashCouponsProductListDto;
        }).collect(Collectors.toList());

        return new PagedOutput(pagedInput, pagedOutput.getTotalElements(), list);
    }

    /**
     * 根据ID查询优惠券门店产品信息
     *
     * @param productIds
     * @param shopId
     * @return
     */
    public List<CashCouponsProductListDto> findCashCouponsProductInfoListByIDs(List<Long> productIds, Long shopId) {
        if (CollectionUtils.isEmpty(productIds) || shopId == null) {
            return null;
        } else {
            List<ProductInfoModel> productInfoModelList = repository.findAll(Q.id.in(productIds).and(Q.shopId.eq(shopId)).and(Q.isSale.eq(true)).and(Q.isDelete.eq(false)));
            List<CashCouponsProductListDto> list = productInfoModelList.stream().map(it -> {
                CashCouponsProductListDto cashCouponsProductListDto = new CashCouponsProductListDto();
                BeanUtils.copyProperties(it, cashCouponsProductListDto);
                //统计库存
                Long stockCount = productCmsSkuService.entityStockCountByProductId(cashCouponsProductListDto.getId());
                cashCouponsProductListDto.setInventory(stockCount);
                return cashCouponsProductListDto;
            }).collect(Collectors.toList());
            return list;
        }

    }


}
